package com.paireach.szwolaiyun.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.paireach.szwolaiyun.R;
import com.paireach.szwolaiyun.fragmentall.DcFinishDischargeCargoFragment;
import com.paireach.szwolaiyun.fragmentall.DcFinishGoodsReceiptFragment;
import com.paireach.szwolaiyun.fragmentall.DcSignFragment;
import com.paireach.szwolaiyun.fragmentall.DcStartDischargeCargoFragment;
import com.paireach.szwolaiyun.fragmentall.FinishDischargeCargoFragment;
import com.paireach.szwolaiyun.fragmentall.FinishGoodsReceiptFragment;
import com.paireach.szwolaiyun.fragmentall.FinishLoadingFragment;
import com.paireach.szwolaiyun.fragmentall.GoodsReceiptFactorySignFragment;
import com.paireach.szwolaiyun.fragmentall.StartDischargeCargoFragment;
import com.paireach.szwolaiyun.fragmentall.StartLoadingFragment;
import com.paireach.szwolaiyun.fragmentall.StraightHairDischargeCargoFragment;
import com.paireach.szwolaiyun.fragmentall.StraightHairFinishGoodsReceiptFragment;
import com.paireach.szwolaiyun.fragmentall.StraightHairSignFragment;
import com.paireach.szwolaiyun.sz_common_widget.activity.BaseActivity;
import com.paireach.szwolaiyun.sz_util.SharedPreferencesUtil;

import szwolaiyun.paireach.com.szwolaizhuang.model.business.DriveOrder;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.AppEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.HttpErrorEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.event.HttpSuccessEvent;
import szwolaiyun.paireach.com.szwolaizhuang.model.requestTag.RequestTag;
import szwolaiyun.paireach.com.szwolaizhuang.net.WayBillRequest;
import szwolaiyun.paireach.com.szwolaizhuang.net.json.JsonPaser;

/**
 * 對應設計圖的B界面，這個界面的主要功能：
 * 1.通過通知啓動這個界面，獲取通知傳遞過來的單號
 * 2.調用接口查詢單號對應的運單詳細信息
 * 3.判斷這個單子的狀態，加載不同的界面
 * 應爲這個界面衹能取到單號，無法直接獲取到運單對象，所以必須調用一次接口來獲運單對象
 * <p/>***注意***
 * <br/>這個界面衹能被通知所調用，<b>禁止任何界面上調用本Activity！</b>
 */
public class Activity_B extends BaseActivity {

    private String orderNo;
    private DriveOrder driveOrder;

    private ProgressBar bar;
    private FrameLayout frameLayout;
    private TextView txt_error;

    private StatusJumpReceiver receiver;
    private AutoFinishReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity__b);
        sendBroadcast(new Intent("com.paireach.szwolaiyun.ACTION_AUTO_FINISH"));
        IntentFilter mFilter = new IntentFilter("com.paireach.szwolaiyun.ACTION_AUTO_FINISH");
        mReceiver = new AutoFinishReceiver();
        registerReceiver(mReceiver, mFilter);
        initData();
        initView();
        getOrderDetail();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.paireach.szwolaiyun.ACTION_JUMP_NON_STICKY");
        registerReceiver(receiver, filter);
    }

    private void initData() {
        orderNo = getIntent().getStringExtra("orderNumber");
        receiver = new StatusJumpReceiver(this);
    }

    private void initView() {
        bar = (ProgressBar) findViewById(R.id.progressBar);
        frameLayout = (FrameLayout) findViewById(R.id.frame);
        txt_error = (TextView) findViewById(R.id.txt_error);
    }

    private void getOrderDetail() {
        Log.e("Activity_B", "开始获取运单详情");
        bar.setVisibility(View.VISIBLE);
        frameLayout.setVisibility(View.GONE);
        txt_error.setVisibility(View.GONE);
        new WayBillRequest().getOrderDetailByOrderNumberAndPhone(orderNo,
                SharedPreferencesUtil.getValue(this, SharedPreferencesUtil.USER_PHONE));
    }

    @Override
    public void applicationEvent(AppEvent event) {
        super.applicationEvent(event);
        if (event.getTag().equals("get_order_detail_info")) {
            bar.setVisibility(View.GONE);
            if (event.getCode() == 0) {//0是JsonParse中设置的
                Log.e("Activity_B", "获取运单详情成功，数据解析成功，开始更换界面");
                driveOrder = (DriveOrder) event.getObj1();
                loadFragments(driveOrder.getOrderStateCode());
            } else {
                Log.e("Activity_B", "获取运单详情成功，数据解释失败，显示错误内容");
                frameLayout.setVisibility(View.GONE);
                txt_error.setVisibility(View.VISIBLE);
                txt_error.setText(event.getExtraInfo());
                showToast(event.getExtraInfo());
            }
        }
    }

    //更换界面
    private void loadFragments(int stateCode) {
        Log.e("Activity_B", "开始更换界面，code=" + stateCode);
        if (stateCode == 224 || stateCode == 226 || stateCode == 236 || stateCode == 238) {
            Log.e("Activity_B", "开始更换界面，判断应该要跳转D界面");
            frameLayout.setVisibility(View.GONE);
            txt_error.setVisibility(View.GONE);
            Bundle bundle = new Bundle();
            bundle.putSerializable("DriveOrder", driveOrder);
            Intent intent = new Intent(this, Activity_D.class);
            intent.putExtras(bundle);
            //finish()有可能没有销毁B，
            Activity_B.this.finish();
            startActivity(intent);
//           finish();
        } else {
            Log.e("Activity_B", "开始更换界面，不跳转D界面，直接在B界面中处理");
            frameLayout.setVisibility(View.VISIBLE);
            txt_error.setVisibility(View.GONE);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            //加載fragment
            switch (stateCode) {
                case 228:
                    //装货中
                    StartLoadingFragment loadingFragment = StartLoadingFragment.getInstance(driveOrder.getOrderNo());
                    transaction.replace(R.id.frame, loadingFragment, StartLoadingFragment.TAG).commit();
                    break;
                case 230:
                    //装货完成正在出厂
                    FinishLoadingFragment fragment5 = FinishLoadingFragment.getInstance(driveOrder.getOrderNo());
                    transaction.replace(R.id.frame, fragment5, FinishLoadingFragment.TAG).commit();
                    break;
                case 232:
                    //送货在途,是可以进行签到的状态
                    if (!TextUtils.isEmpty(driveOrder.getDcDeptType())) {
                        if (driveOrder.getDcDeptType().equals("dc")) {
                            //dc 签到
                            DcSignFragment fragment1 = DcSignFragment.getInstance(driveOrder);
                            transaction.replace(R.id.frame, fragment1, DcSignFragment.TAG).commit();
                        } else if (driveOrder.getDcDeptType().equals("factory")) {
                            //工厂签到
                            GoodsReceiptFactorySignFragment fragment1 = GoodsReceiptFactorySignFragment.getInstance(driveOrder);
                            transaction.replace(R.id.frame, fragment1, GoodsReceiptFactorySignFragment.TAG).commit();
                        }
                    } else {
                        if (!TextUtils.isEmpty(driveOrder.getAlloStraType())) {
                            StraightHairSignFragment fragment = StraightHairSignFragment.getInstance(driveOrder);
                            transaction.replace(R.id.frame, fragment, StraightHairSignFragment.TAG).commit();
                        } else {
                            showToast("状态" + stateCode + ";DcDeptType=null & AlloStraType=null,请联系飞哥查找问题原因!");
                            frameLayout.setVisibility(View.GONE);
                            txt_error.setVisibility(View.VISIBLE);
                            txt_error.setText("状态" + stateCode + ";DcDeptType=null & AlloStraType=null,请联系飞哥查找问题原因!");
                        }
                    }
                    break;
                case 240:
                    //收货中
                    if (driveOrder.getDcDeptType().equals("dc")) {
                        DcStartDischargeCargoFragment fragment1 = DcStartDischargeCargoFragment.getInstance(driveOrder.getOrderNo());
                        transaction.replace(R.id.frame, fragment1, DcStartDischargeCargoFragment.TAG).commit();
                    } else if (driveOrder.getDcDeptType().equals("factory")) {
                        StartDischargeCargoFragment fragment6 = StartDischargeCargoFragment.getInstance(driveOrder.getOrderNo());
                        transaction.replace(R.id.frame, fragment6, StartDischargeCargoFragment.TAG).commit();
                    }
                    break;
                case 242:
                    //离厂(收)中
                    if (driveOrder.getDcDeptType().equals("dc")) {
                        DcFinishDischargeCargoFragment fragment1 = DcFinishDischargeCargoFragment.getInstance(driveOrder.getOrderNo());
                        transaction.replace(R.id.frame, fragment1, DcFinishDischargeCargoFragment.TAG).commit();
                    } else if (driveOrder.getDcDeptType().equals("factory")) {
                        FinishDischargeCargoFragment fragment3 = FinishDischargeCargoFragment.getInstance(driveOrder.getOrderNo());
                        transaction.replace(R.id.frame, fragment3, FinishDischargeCargoFragment.TAG).commit();
                    }
                    break;
                case 246:
                    //直发专用：卸货中
                    StraightHairDischargeCargoFragment fragment = StraightHairDischargeCargoFragment.getInstance(driveOrder);
                    transaction.replace(R.id.frame, fragment, StraightHairDischargeCargoFragment.TAG).commit();
                    break;
                case 247:
                    //直发专用：完成
                    transaction.replace(R.id.frame, new StraightHairFinishGoodsReceiptFragment(), "StraightHairFinishGoodsReceiptFragment").commit();
                    break;
                case 244:
                case 248:
                    if (driveOrder.getDcDeptType().equals("dc")) {
                        DcFinishGoodsReceiptFragment fragment1 = new DcFinishGoodsReceiptFragment();
                        transaction.replace(R.id.frame, fragment1, DcFinishGoodsReceiptFragment.TAG).commit();
                    } else if (driveOrder.getDcDeptType().equals("factory")) {
                        FinishGoodsReceiptFragment fragment3 = new FinishGoodsReceiptFragment();
                        transaction.replace(R.id.frame, fragment3, FinishGoodsReceiptFragment.TAG).commit();
                    }
                    break;
                default:
                    //該狀態沒有被記錄！
                    showToast("沒有對" + stateCode + "這個狀態進行界面繪製");
                    frameLayout.setVisibility(View.GONE);
                    txt_error.setVisibility(View.VISIBLE);
                    txt_error.setText("沒有對" + stateCode + "這個狀態進行界面繪製");
                    break;
            }
        }
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        if (event.getRequestTag() == RequestTag.GET_ORDER_DETAIL) {
            Log.e("Activity_B", "获取运单详情失败，显示失败内容");
            bar.setVisibility(View.GONE);
            frameLayout.setVisibility(View.GONE);
            txt_error.setVisibility(View.VISIBLE);
            txt_error.setText(event.getErrorMessage());
            showToast(event.getErrorMessage());
        }
    }

    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        if (event.getRequestTag() == RequestTag.GET_ORDER_DETAIL) {
            Log.e("Activity_B", "获取运单详情成功，开始解析数据");
            txt_error.setVisibility(View.GONE);
            bar.setVisibility(View.VISIBLE);
            frameLayout.setVisibility(View.GONE);
            JsonPaser.parseDriverOrderDetail(event.getJson());
        }
    }

    /**
     * 在这个B界面上 只需要更换fragment即可，很简单<br/>
     * 在其他界面上直接使用单独文件的receiver，里面做一个跳转B/C界面的操作即可
     */
    private class StatusJumpReceiver extends BroadcastReceiver {

        private String action1 = "com.paireach.szwolaiyun.ACTION_JUMP_NON_STICKY";
        private String orderNumber;
        private Activity mContext;

        public StatusJumpReceiver(Activity mContext) {
            this.mContext = mContext;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(action1)) {
                Log.e("Activity_B", "收到内部广播消息，应该要重新获取运单详细");
                //解析数据
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    orderNumber = bundle.getString("orderCode");
                    orderNo = orderNumber;
                    getOrderDetail();
                }
            }
        }
    }

    private class AutoFinishReceiver extends BroadcastReceiver {
        private String action2 = "com.paireach.szwolaiyun.ACTION_AUTO_FINISH";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(action2)) {
                Activity_B.this.finish();
            }
        }
    }

}
